﻿using System.Collections.Generic;
using System.Web.Script.Serialization;
using Synology.DS.Interface.Entities.DiskStation;
using Synology.DS.Interface.Exception;

namespace Synology.DS.Core.DiskStation
{
    public class AuthService
    {
        private readonly StationAccessor _accessor;

        public AuthService(StationAccessor accessor)
        {
            _accessor = accessor;
        }

        public ServiceInfo QueryInfo()
        {
            object request = new
            {
                api = "SYNO.API.Info",
                method = "query",
                query = "SYNO.API.Auth",
                version = 1
            };

            Response response = _accessor.SubmitGetRequest("query.cgi", request);
            if (!response.success)
                throw new AccessDiskStationException(response.error.code);

            Dictionary<string, object> resultedDictionary = response.data;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.ConvertToType<ServiceInfo>(resultedDictionary["SYNO.API.Auth"]);
        }

        public string Login(ServiceInfo info, string user, string password, string session)
        {
            object request = new
            {
                api = "SYNO.API.Auth",
                version = info.maxVersion,
                method = "login",
                account = user,
                passwd = password,
                session = session,
                format = "cookie",
            };

            Response response = _accessor.SubmitGetRequest(info.path, request);
            if (!response.success)
                throw new AccessDiskStationException(response.error.code);

            return response.data["sid"];
        }

        public void Logout(ServiceInfo info, string session)
        {
            object request = new
            {
                api = "SYNO.API.Auth",
                version = info.maxVersion,
                method = "logout",
                session = session,
            };

            Response response = _accessor.SubmitGetRequest(info.path, request);
            if (!response.success)
                throw new AccessDiskStationException(response.error.code);
        }
    }
}
